<template>
	<view>

		<view style="padding: 20upx;background-color: #FFFFFF;">

			<scroll-view scroll-y :style="{ 'height':scrollHeight }">
				<view style="text-align: center;font-weight: bold; margin-bottom: 20rpx;">
					{{protocol.title||""}}
				</view>
				<view>
					<rich-text :nodes="protocol.content" style="white-space: pre-wrap;"></rich-text>
				</view>

			</scroll-view>

			<catSignatureVue ref="sig" :visible='visible' @close="catClose" @save='getImage'></catSignatureVue>

			<view id="applyBottom"
				style="display: flex;position: fixed;flex-direction: column;border-top: 1px solid #F5F5F5; bottom: 0;left: 0; padding: 30upx;background-color: #FFFFFF;">
				<view style="padding 20px 10px; font-size: 14px; color:#ff7700;margin: 10px 0px ">
					请您仔细阅读上述协议内容,如无任何异议请签上姓名并提交。
				</view>
				<view
					style="display: flex; flex-direction: row;height: 220rpx; text-align: center; border: 1px solid @eee;"
					class="items-center;">

					<view style="flex: 1; " @click="checkagree">
						<view v-if="!imageCode">请在此处签名</view>
						<image :src="imageCode" style='height:  220rpx' mode="heightFix" v-if="imageCode" />
					</view>
				</view>
				<view v-if="level == 'AG_WHS'||level == 'MANAGER'">
					<view v-if="level == 'AG_WHS'"
						style="padding 20px 10px; font-size: 14px; color:#ff7700;margin: 10px 0px ">
						请您上传营业执照扫描图片
					</view>
					<view v-if="level == 'MANAGER'"
						style="padding 20px 10px; font-size: 14px; color:#ff7700;margin: 10px 0px ">
						请您上传纸质协议扫描图片
					</view>
					<u-upload :fileList="fileList6" @afterRead="afterRead" @delete="deletePic" name="6" multiple
						:maxCount="1" width="100px" height="100px">
						<view class="flex-col justify-center items-center">
							<view style="width: 100px; height: 100px;background-color: #fdfdfd;"
								class="flex-col justify-center items-center">
								<image :src="fileName?fileName:`../../static/image/pic.png`" mode="aspectFill"
									style="width: 100rpx;height: 100rpx;">
								</image>
								<view style="color: #888; padding: 10px;" v-if="!userInfo.user.meta.qrCode">在此上传
								</view>
							</view>
						</view>


					</u-upload>
				</view>
				<view style="margin-top:20rpx">
					<button type="primary" @click="saveContractBefore" :disabled="submited">提交</button>
				</view>

			</view>
		</view>
		<u-toast ref="utoast"></u-toast>
	</view>
</template>

<script>
	import Utils from '../../common/Utils.js'
	import catSignatureVue from './components/cat-signature/cat-signature.vue'
	export default {
		components: {
			catSignatureVue
		},
		data() {
			return {
				protocol: {},
				checked: false,
				visible: false,
				imageCode: "",
				Binded: false,
				messageText: '',
				loaded: false,
				scrollHeight: "",
				student: {},
				signFile: null,
				uploadBuffer: null,
				singUrl: "",
				uploadPath: "",
				userInfo: "",
				submited: false,
				applyUrl: "/shop/applications",
				protocolUrl: "/protocols/shop_protocol/latest",
				evaluationId: "",
				roles: '',
				level: "",
				fileList6: [],
				fileName: "",
			}
		},
		onLoad(options) {
			if (options.id) {
				this.evaluationId = options.id;
			}

			if (options.level) {
				let title = `申请${this.$Utils.getUserLevel(options.level)}`
				uni.setNavigationBarTitle({
					title: title
				})
				this.level = options.level;
				console.log("level=", this.level)
				if (options.level == 'AG_WHS') {
					this.protocolUrl = `/protocols/whs_protocol/latest`
					this.applyUrl = '/whs/applications'
				} else if (options.level == 'AG_AGENT') {
					this.protocolUrl = `/protocols/agent_protocol/latest`
					this.applyUrl = '/agent/applications'
				} else if (options.level == 'MANAGER') {
					this.protocolUrl = `/protocols/manager_protocol/latest`
					this.applyUrl = '/manager/applications'
				}
			} else {
				this.protocolUrl = `/protocols/shop_protocol/latest`
				this.applyUrl = '/shop/applications'
			}
			this.$nextTick(() => {
				let _me = this;
				uni.getSystemInfo({
					success(res) {
						var tempHeight = res.windowHeight;
						console.log(tempHeight)
						uni.createSelectorQuery().select("#applyBottom").fields({
							size: true,
							scrollOffset: true
						}, (data) => {
							console.log(data.height)
							tempHeight -= data.height;

							console.log("减掉顶部后的高度 " + tempHeight);
							_me.scrollHeight = tempHeight - 20 + 'px';
						}).exec();

					}
				});
			})


			this.getContract()


		},
		onShow() {
			uni.getSystemInfo({
				success: (res) => {
					this.scrollHeight = `${res.windowHeight-420}px`;
				}
			});

		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'success',
						message: '上传中'
					})
				});

			},
			getContract(contracId, url) {
				this.$get({
					url: `${this.$Utils.ApiUrl}${this.protocolUrl}`,
					data: {

					}
				}).then(res => {
					this.protocol = res;

					console.log(res)
				})

			},

			catClose() {
				this.visible = false;
			},
			checkagree() {
				this.visible = true;
			},
			getImage(dataUrl) {
				this.imageCode = dataUrl;

				console.log(dataUrl);
				this.visible = false;
				this.checked = true;
			},

			guid() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = Math.random() * 16 | 0,
						v = c == 'x' ? r : (r & 0x3 | 0x8);
					return v.toString(16);
				});
			},
			saveContractBefore() {
				this.$Utils.SubscribeMessage('d5Jcf2n5nvxuehLqpZ6tEnbhJhjEu6tNww5-SPM0ifY', () => {
					this.saveContract()
				})


			},
			uploadFilePromise(path, aRes) {
				let _that = this;
				let ext = path.substring(path.lastIndexOf('.'))
				let _fileKey = `images/${this.userInfo.Name}_${Utils.guid()}${ext}`;
				return new Promise((resolve, reject) => {


					wx.uploadFile({
						url: aRes.Host, //仅为示例，非真实的接口地址
						filePath: path,
						name: 'file',
						formData: {
							key: _fileKey,
							'Policy': aRes.Policy, //后端Base64编码格式的授权策略 用于签名
							'OSSAccessKeyId': aRes.AccessKeyId, //OSS控制台获取
							'Success_Action_Status': '200', //让服务端返回200,不然，成功上传图片后阿里默认返回statusCode: 204
							'Signature': aRes.Signature, //服务端返回的签名内容 
						},
						success(res) {
							console.log(res)
							if (res.errMsg == 'uploadFile:ok') {
								resolve(`${ aRes.Host}/${_fileKey}`)
							}


						},
						fail(err) {
							console.log(err)
							reject(err)
							uni.showToast({
								title: '上传失败',
								icon: 'none'
							});

						}
					})
				})

			},
			saveContract() {

				var _that = this;
				if (!this.imageCode) {
					uni.showToast({
						title: `请先签名`,
						icon: 'none'
					});
					return;
				}
				if (this.level == 'AG_WHS') {
					if (this.fileList6.length == 0) {
						uni.showToast({
							title: `请您上传营业执照扫描照照片`,
							icon: 'none'
						});
						return
					}

				} else if (this.level == 'MANAGER') {
					if (this.fileList6.length == 0) {
						uni.showToast({
							title: `请您上传纸质协议扫描照照片`,
							icon: 'none'
						});
						return
					}

				}
				this.submited = true;
				let user = this.$store.state.userInfo;


				_that.$get({
					url: `${Utils.ApiUrl}/files/signature`,
					data: {
						dir: 'images/'
					}
				}).then(async (aRes) => {
					const result = await _that.uploadFilePromise(this.imageCode, aRes);


					if (_that.evaluationId) {
						let postData = {
							signatureUrl: result,
							protocolId: _that.protocol.id,
							evaluationId: _that.evaluationId
						}
						if (_that.fileList6.length > 0) {
							const picUrl = await _that.uploadFilePromise(_that.fileList6[0].url, aRes);
							if (_that.level == 'AG_WHS') {
								_that.$set(postData, 'licenseUrl', picUrl);
							} else if (_that.level == 'MANAGER') {
								_that.$set(postData, 'contract', picUrl);
							}
						}

						console.log(postData)
						_that.doPost(postData)


					} else {
						let postData = {
							signatureUrl: result,
							protocolId: _that.protocol.id

						}
						console.log(postData)
						_that.doPost(postData)

					}



				})
				return;
			},

			doPost(postData) {
				let that = this;
				this.$post({
					url: Utils.ApiUrl + this.applyUrl,
					data: postData,
				}).then((res) => {
					console.log(res.data);
					this.$refs.utoast.show({
						message: "申请成功",
						complete() {
							uni.switchTab({
								url: '/pages/my/my'
							})
						}
					})
				}).catch((err) => {
					that.Binded = true;
				})
			}
		}
	}
</script>

<style>

</style>